package com.zhhtech.zhh.ui.activity.commom

import android.view.View
import androidx.core.view.isVisible
import com.mobile.auth.gatewayauth.ResultCode
import com.zhhtech.zhh.api.api
import com.zhhtech.zhh.api.core.FirmException
import com.zhhtech.zhh.api.core.launchUI
import com.zhhtech.zhh.api.core.toData
import com.zhhtech.zhh.common.AGREEMENT
import com.zhhtech.zhh.common.PRIVACY_POLICY
import com.zhhtech.zhh.common.UserCache
import com.zhhtech.zhh.databinding.ActivityLoginBinding
import com.zhhtech.zhh.ui.activity.main.MainActivity
import com.zhhtech.zhh.ui.api.ApiObserver
import com.zhhtech.zhh.ui.base.BaseActivity
import com.zhhtech.zhh.ui.ext.ACTION_USER_LOGIN
import com.zhhtech.zhh.ui.ext.startActivityExt
import com.zhhtech.zhh.ui.ext.toastMessageLong
import com.zhhtech.zhh.ui.ext.value
import com.zhhtech.zhh.ui.helper.PhoneAuthHelper
import com.zhhtech.zhh.ui.helper.getImei
import com.zhhtech.zhh.ui.helper.localSendBroadcast
import com.zhhtech.zhh.ui.utils.ActivityManger
import com.zhhtech.zhh.ui.utils.GlideUtils
import com.zhhtech.zhh.ui.utils.SPUtils
import com.zhhtech.zhh.ui.utils.Utils
import com.zhhtech.zhh.R

class LoginActivity : BaseActivity<ActivityLoginBinding>() {
    private lateinit var mPhoneAuthHelper: PhoneAuthHelper
    private var vcodeLogin = true
    override fun initView() {
        super.initView()
        Utils.invasionStatusBar(this)
        ActivityManger.finishAllActivity(LoginActivity::class.java)
        GlideUtils.intoRoundedCorners(this, R.mipmap.logo, vb.ivLogo)
        bindViewClick(
            vb.buttonLogin, vb.tbVcode, vb.autoButtonLogin, vb.tvLoginModel,
            vb.tvPrivacyPolicy, vb.tvAgreement
        )
        initServiceClause()

        mPhoneAuthHelper = PhoneAuthHelper(this)
        launchUI({
            mPhoneAuthHelper.checkEnvAvailable()
            changeLoginModel(!vcodeLogin)
        })
//        vb.etPhone.setText(SPUtils.getString("key_phone"))
//        vb.etPassword.setText(SPUtils.getString("key_password"))
    }

    private fun changeLoginModel(vcodeLogin: Boolean) {
        if (vcodeLogin) {
            vb.llPhoneLogin.isVisible = true
            vb.autoButtonLogin.isVisible = false
            vb.tvLoginModel.text = "一键登录"
        } else {
            vb.llPhoneLogin.isVisible = false
            vb.autoButtonLogin.isVisible = true
            vb.tvLoginModel.text = "验证码登录"
        }
        this.vcodeLogin = vcodeLogin
    }

    override fun onClick(v: View?) {
        when (v) {
            vb.tbVcode -> launchUI({
                api.codeSend(vb.etPhone.value).toData()
                vb.tbVcode.start()
            }, ApiObserver(mThis))

            vb.tvLoginModel -> {
                changeLoginModel(!vcodeLogin)
            }

            vb.autoButtonLogin -> {
                Utils.hideSoftInput(this)
                if (!vb.cbServiceClause.isChecked) {
                    "请先同意隐私政策和用户协议".toastMessageLong()
                    return
                }
                SPUtils.put("service_clause", vb.cbServiceClause.isChecked)
                launchUI({
                    val token = mPhoneAuthHelper.getLoginToken()
                    val tokenBean = api.aliClickLogin(token, getImei()).toData()
                        ?: throw FirmException("登录失败")
                    UserCache.saveToken(tokenBean.token)
                    UserCache.saveUserInfoBean(api.userInfo().toData())
                }, ApiObserver(this, commonButton = vb.autoButtonLogin, error = {
                    if (it is FirmException && it.code == ResultCode.CODE_FAILED.toInt()) {
                        "一键登录失败切换到其他登录方式".toastMessageLong()
                        changeLoginModel(!vcodeLogin)
                    }
                }, success = ::success))
            }

            vb.buttonLogin -> {
                Utils.hideSoftInput(this)
                if (!vb.cbServiceClause.isChecked) {
                    "请先同意隐私政策和用户协议".toastMessageLong()
                    return
                }
                SPUtils.put("service_clause", vb.cbServiceClause.isChecked)
                launchUI({
                    val tokenBean = api.userLogin(
                        vb.etPhone.value,
                        vb.etVcode.value, getImei()
                    ).toData() ?: throw FirmException("登录失败")
                    UserCache.saveToken(tokenBean.token)
                    UserCache.saveUserInfoBean(api.userInfo().toData())
                }, ApiObserver(this, commonButton = vb.buttonLogin, success = ::success))
            }

            vb.tvPrivacyPolicy -> openUrl(PRIVACY_POLICY)
            vb.tvAgreement -> openUrl(AGREEMENT)
        }
    }

    private fun success(any: Any?) {
        goMain()
//        setResult(RESULT_OK)
//        finish()
        localSendBroadcast(ACTION_USER_LOGIN)
    }

    private fun goMain() {
        startActivityExt<MainActivity>()
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
        finish()
    }

    private fun initServiceClause() {
        vb.cbServiceClause.isChecked = SPUtils.getBoolean("service_clause", false)
    }
}